import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bmfmap_example/DemoPages/Map/show_map_type_page.dart';
import 'package:flutter_bmfmap_example/componets/text/rounded_input_field.dart';
import 'package:flutter_bmfmap_example/componets/text/rounded_password_field.dart';
import 'package:flutter_bmfmap_example/componets/text/whiteh2.dart';
import 'package:flutter_bmfmap_example/componets/text/whitetittle.dart';
import 'package:flutter_bmfmap_example/flutter_map_demo.dart';
import 'package:flutter_bmfmap_example/http/http.dart';
import 'package:flutter_bmfmap_example/models/marketinfomodel.dart';
import 'package:flutter_bmfmap_example/models/userinformodel.dart';
import 'package:flutter_bmfmap_example/pages/RootPage.dart';
import 'package:flutter_bmfmap_example/service/loginserver.dart';
import 'package:flutter_bmfmap_example/tool/HYSizeFit%20.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
  Animation<double> circletop;
  AnimationController circlecontroller;

  Animation<double> tittletop;
  AnimationController tittlecontroller;

  bool islogin = true;

  String email = '276840251@qq.com';
  String password = '123456';

  String registnickname = '';
  String registemail = '';
  String registpassword1 = '';
  String registpassword2 = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    tittlecontroller = new AnimationController(
        duration: Duration(milliseconds: 800), vsync: this);

    circlecontroller = new AnimationController(
        duration: Duration(milliseconds: 1600), vsync: this);

    final CurvedAnimation tittlecurve =
        new CurvedAnimation(parent: tittlecontroller, curve: Curves.easeIn);

    final CurvedAnimation curve =
        new CurvedAnimation(parent: circlecontroller, curve: Curves.easeIn);

    tittletop =
        new Tween(begin: HYSizeFit.setRpx(40), end: HYSizeFit.setRpx(-540))
            .animate(tittlecurve)
              ..addListener(() {
                setState(() {
                  // the state that has changed here is the animation object’s value
                });
              });
    circletop = new Tween(
            begin: -HYSizeFit.setRpx(1600),
            end: HYSizeFit.screenHeight - HYSizeFit.setRpx(340))
        .animate(curve)
          ..addListener(() {
            setState(() {
              // the state that has changed here is the animation object’s value
            });
          });

    // circlecontroller.forward();
  }

  @override
  Widget build(BuildContext context) {
    // print(MediaQuery.of(context).size.height);
    return Scaffold(
      body: SingleChildScrollView(
        child: Container(
          height: HYSizeFit.screenHeight,
          child: Stack(
            alignment: Alignment.center,
            children: [
              _buildbody(),
              _buildcircle(),
              _buildtille(),
            ],
          ),
        ),
      ),
    );
  }

  _buildcircle() {
    return Positioned(
      top: circletop.value.toDouble(),
      child: Container(
        height: HYSizeFit.setRpx(2000),
        width: HYSizeFit.setRpx(2000),
        decoration: BoxDecoration(
          borderRadius: new BorderRadius.circular(HYSizeFit.setRpx(1000)),
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color.fromRGBO(249, 210, 220, 1),
              Color.fromRGBO(253, 190, 206, 1),
            ],
          ),
        ),
      ),
    );
  }

  _buildtille() {
    return Positioned(
      top: tittletop.value,
      child: Container(
        // height: HYSizeFit.screenHeight,
        // width: HYSizeFit.screenWidth,
        child: Column(
          children: [
            SizedBox(
              height: HYSizeFit.setRpx(24),
            ),
            Whitetittle('安全'),
            SizedBox(
              height: HYSizeFit.setRpx(8),
            ),
            Container(
              width: HYSizeFit.setRpx(560),
              child: WhiteH2('给家人一个安全的保障，让每一个人都能幸福，快乐的成长！'),
            ),
            SizedBox(
              height: HYSizeFit.setRpx(16),
            ),
            InkWell(
              onTap: () {
                circlecontroller.forward();
                Future.delayed(Duration(milliseconds: 800), () {
                  print('延时2s执行');
                  // showlogin = !showlogin;
                  tittlecontroller.forward();
                });

                Future.delayed(Duration(milliseconds: 1000), () {
                  islogin = false;
                });
              },
              child: _buildbutton('注册'),
            ),

            SizedBox(
              height: HYSizeFit.screenHeight,
            ),
            // Spacer(),

            Whitetittle('舒适'),
            SizedBox(
              height: HYSizeFit.setRpx(8),
            ),
            Container(
              width: HYSizeFit.setRpx(560),
              child: WhiteH2('实时监测，给你的家人更好的呵护！'),
            ),
            SizedBox(
              height: HYSizeFit.setRpx(16),
            ),
            InkWell(
              onTap: () {
                circlecontroller.reverse();
                Future.delayed(Duration(milliseconds: 800), () {
                  print('延时2s执行');
                  // islogin = !islogin;
                  tittlecontroller.reverse();
                });

                Future.delayed(Duration(milliseconds: 800), () {
                  islogin = true;
                });
              },
              child: _buildbutton('登录'),
            ),
          ],
        ),
      ),
    );
  }

  _buildbutton(String name) {
    return Container(
      width: 88,
      height: 40,
      decoration: new BoxDecoration(
        border: Border.all(color: Colors.white, width: 2), //边框
        borderRadius: new BorderRadius.circular(
          (56.0),
        ),
      ),
      child: Center(
        child: Text(
          name,
          style: TextStyle(
              color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600),
        ),
      ),
    );
  }

  _buildbody() {
    return Positioned(
      top: HYSizeFit.setRpx(600) + tittletop.value,
      child: Container(
        width: HYSizeFit.screenWidth,
        height: HYSizeFit.screenHeight,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
              top: HYSizeFit.setRpx(0),
              child: Offstage(
                offstage: !islogin,
                child: Text(
                  '登录',
                  style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600),
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(350),
              child: Offstage(
                offstage: !islogin,
                child: RoundedInputField(
                  hintText: "邮箱",
                  icon: Icons.email,
                  onChanged: (value) {
                    email = value;
                  },
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(520),
              child: Offstage(
                offstage: !islogin,
                child: PassWordField(
                  hintText: "密码",
                  onChanged: (value) {
                    password = value;
                  },
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(80),
              child: Offstage(
                offstage: !islogin,
                child: Image.asset(
                  'assets/images/common/login.png',
                  width: HYSizeFit.setRpx(560),
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(690),
              child: Offstage(
                offstage: !islogin,
                child: InkWell(
                  onTap: () {
                    _login();
                  },
                  child: Container(
                    width: HYSizeFit.setRpx(380),
                    height: 56,
                    decoration: new BoxDecoration(
                      color: Color.fromRGBO(255, 173, 61, 1),
                      borderRadius: new BorderRadius.circular(
                        (56.0),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        '登录',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(0),
              child: Offstage(
                offstage: islogin,
                child: Text(
                  '注册',
                  style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600),
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(120),
              child: Offstage(
                offstage: islogin,
                child: Image.asset(
                  'assets/images/common/regist.png',
                  width: HYSizeFit.setRpx(520),
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(350),
              child: Offstage(
                offstage: islogin,
                child: RoundedInputField(
                  hintText: "昵称",
                  icon: Icons.person,
                  onChanged: (value) {
                    registnickname = value;
                  },
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(520),
              child: Offstage(
                offstage: islogin,
                child: RoundedInputField(
                  hintText: "邮箱",
                  icon: Icons.email,
                  onChanged: (value) {
                    registemail = value;
                  },
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(1030),
              child: Offstage(
                offstage: islogin,
                child: InkWell(
                  onTap: () {
                    _regist();
                  },
                  child: Container(
                    width: HYSizeFit.setRpx(380),
                    height: 56,
                    decoration: new BoxDecoration(
                      color: Color.fromRGBO(255, 173, 61, 1),
                      borderRadius: new BorderRadius.circular(
                        (56.0),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        '注册',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(690),
              child: Offstage(
                offstage: islogin,
                child: PassWordField(
                  hintText: "密码",
                  onChanged: (value) {
                    registpassword1 = value;
                  },
                ),
              ),
            ),
            Positioned(
              top: HYSizeFit.setRpx(860),
              child: Offstage(
                offstage: islogin,
                child: PassWordField(
                  hintText: "确认密码",
                  onChanged: (value) {
                    registpassword2 = value;
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _login() async {
    if (!Loginserver.isEmail(email)) {
      Fluttertoast.showToast(msg: "邮箱格式不正确");
      return;
    }
    if (password.length == 0) {
      Fluttertoast.showToast(msg: "请输入密码");
      return;
    }
    var result = await Loginserver.login(email, password).catchError((value) {
      Fluttertoast.showToast(msg: "网络错误");
    });
    if (result['msg'] == '操作成功') {
      Map<String, String> headers = {'Authorization': result['data']};
      Http.setHeaders(headers);
      Fluttertoast.showToast(
        msg: "登陆成功",
      );
      await _getuserinfor();
       
      // Provider.of<Userinfomodel>(context).setnickname('yummy');
      if(mounted)Navigator.pushAndRemoveUntil(
        context,
        new MaterialPageRoute(builder: (context) => new RootPage()),
        (route) => route == null,
      );
    } else if (result['msg'] == '用户名或密码错误') {
      Fluttertoast.showToast(
        msg: "用户名或密码错误",
      );
    }
    print(result);
  }

  _regist() async {
    if (registnickname.length == 0) {
      Fluttertoast.showToast(msg: "请输入昵称");
      return;
    }
    if (!Loginserver.isEmail(registemail)) {
      Fluttertoast.showToast(msg: "邮箱格式不正确");
      return;
    }
    if (registpassword1.length == 0) {
      Fluttertoast.showToast(msg: "请输入密码");
      return;
    }
    if (registpassword2.length == 0) {
      Fluttertoast.showToast(msg: "请输入确认密码");
      return;
    }
    if (registpassword1 != registpassword2) {
      Fluttertoast.showToast(msg: "两次密码不一致");
      return;
    }
    var result = await Loginserver.regist(
            registnickname, email, registpassword1, registpassword2)
        .catchError((value) {
      Fluttertoast.showToast(msg: "网络错误");
    });
    // if (result['msg'] == '操作成功') {
    //   Map<String, String> headers = {'Authorization': result['data']};
    //   Http.setHeaders(headers);
    //   Fluttertoast.showToast(
    //     msg: "登陆成功",
    //   );
    // } else if (result['msg'] == '用户名或密码错误') {
    //   Fluttertoast.showToast(
    //     msg: "用户名或密码错误",
    //   );
    // }
    print(result);
  }

  _getuserinfor() async {
    // var result1 = await Http.get('/user/upload?url=http%3A%2F%2Fxiangrikui.resource.vaiwan.com%2F2021%2F07%2F20%2F69611d1a-affa-4984-aad4-e07010658077.jpg')
    //     .catchError((value) => Fluttertoast.showToast(msg: "网络错误"));

    var result = await Http.get('/user/getUserInfo')
        .catchError((value) => Fluttertoast.showToast(msg: "网络错误"));
    print(result);
    context.read<Userinfomodel>().setuserId(email);
    context.read<Userinfomodel>().setnickname(result['nickname']);
    context.read<Userinfomodel>().setportraiturl(result['portrait']);
    
  }
}
